package com.fyb.basic.lock.thread;

import java.util.Random;

/**
 * 模拟多线程售票系统的实现，其中10个线程分别代表10个售票窗口，
 * 并通过同步机制保证线程安全，避免多个线程同时修改剩余票数
 */
public class TicketSystemDemo {
    /**
     * 总票数
     */
    private static final int TOTAL_TICKETS = 1000;
    /**
     * 剩余票数
     */
    private static int remainingTICKETS = TOTAL_TICKETS;
    /**
     * 锁对象，用于同步
     */
    private static final Object lock = new Object();

    public static void main(String[] args) {
        // 创建并启动10个线程，模拟10个售票窗口
        for (int i = 0; i < 10; i++) {
            new Thread(new TicketSeller(i)).start();
        }
    }

    /**
     * TicketSeller类实现了Runnable接口，代表售票窗口的线程任务
     */
    private static class TicketSeller implements Runnable {
        private int windowNumber;
        public TicketSeller(int windowNumber) {
            this.windowNumber = windowNumber;
        }
        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    if (remainingTICKETS > 0) {
                        try {
                            // 模拟购票时间
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        // 购票操作
                        buyTicket();
                    } else {
                        break; // 没有票了，跳出循环
                    }
                }
                // 模拟购票后的其他操作，增加随机性
                try {
                    Thread.sleep((long) (Math.random() * 1000));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        /**
         * 购票操作
         */
        private void buyTicket() {
            // 模拟随机购票数
            int number = new Random().nextInt(10);
            if (remainingTICKETS >= number && number > 0) {
                remainingTICKETS = remainingTICKETS - number;
                System.out.println("从窗口 G1000" + windowNumber + " 购买了 " + number + " 张票, 还剩 " + remainingTICKETS + " 张票");
            }
        }
    }
}

